package com.kalvan.core.utils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.Set;

/**
 * @author chenliang
 */
public class ValidationUtil {
    private static final Validator VALIDATOR;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        VALIDATOR = factory.getValidator();
    }

    public ValidationUtil() {
    }

    public static String validation(Object obj, Class[] verfiyGroup) {
        Set<ConstraintViolation<Object>> set = null;
        if (verfiyGroup != null) {
            set = VALIDATOR.validate(obj, verfiyGroup);
        } else {
            set = VALIDATOR.validate(obj);
        }

        return set != null && set.size() > 0 ? getValidateErrMsg(set) : null;
    }

    private static String getValidateErrMsg(Set<ConstraintViolation<Object>> set) {
        StringBuilder builder = new StringBuilder();
        Iterator var2 = set.iterator();

        while (var2.hasNext()) {
            ConstraintViolation<Object> constraintViolation = (ConstraintViolation) var2.next();
            builder.append(constraintViolation.getMessage()).append(",");
        }

        return builder.substring(0, builder.length() - 1);
    }
}
